// script.js - 任务记录网站交互逻辑

class TaskManager {
    constructor() {
        this.taskList = document.getElementById('taskList');
        this.taskInput = document.getElementById('taskInput');
        this.addTaskBtn = document.getElementById('addTaskBtn');
        
        this.loadTasks();
        this.bindEvents();
    }

    bindEvents() {
        // 添加任务
        this.addTaskBtn.addEventListener('click', () => this.addTask());
        this.taskInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') this.addTask();
        });

        // 事件委托：处理复选框和删除按钮
        this.taskList.addEventListener('change', (e) => {
            if (e.target.classList.contains('task-checkbox')) {
                this.toggleTaskStatus(e.target);
            }
        });

        this.taskList.addEventListener('click', (e) => {
            if (e.target.classList.contains('delete-btn')) {
                this.deleteTask(e.target);
            }
        });
    }

    addTask() {
        const text = this.taskInput.value.trim();
        if (!text) return;

        const newTask = {
            id: Date.now().toString(),
            text: text,
            completed: false,
            createdAt: new Date().toISOString()
        };

        this.saveTask(newTask);
        this.renderTask(newTask);
        this.taskInput.value = '';
        this.taskInput.focus();

        // 更新空状态
        this.updateEmptyState();
    }

    renderTask(task) {
        const li = document.createElement('li');
        li.className = `task-item ${task.completed ? 'completed' : ''}`;
        li.dataset.id = task.id;

        li.innerHTML = `
            <input type="checkbox" class="task-checkbox" ${task.completed ? 'checked' : ''}>
            <span class="task-text">${this.escapeHtml(task.text)}</span>
            <button class="delete-btn" aria-label="删除任务">删除</button>
        `;

        this.taskList.appendChild(li);
    }

    toggleTaskStatus(checkbox) {
        const li = checkbox.closest('.task-item');
        const taskId = li.dataset.id;

        li.classList.toggle('completed', checkbox.checked);

        // 更新本地存储
        const tasks = this.getTasks();
        const taskIndex = tasks.findIndex(t => t.id === taskId);
        if (taskIndex !== -1) {
            tasks[taskIndex].completed = checkbox.checked;
            localStorage.setItem('tasks', JSON.stringify(tasks));
        }
    }

    deleteTask(button) {
        const li = button.closest('.task-item');
        const taskId = li.dataset.id;

        li.remove();

        // 从本地存储移除
        let tasks = this.getTasks();
        tasks = tasks.filter(t => t.id !== taskId);
        localStorage.setItem('tasks', JSON.stringify(tasks));

        // 更新空状态
        this.updateEmptyState();
    }

    loadTasks() {
        const tasks = this.getTasks();
        if (tasks.length === 0) {
            this.showEmptyState();
        } else {
            tasks.forEach(task => this.renderTask(task));
        }
    }

    getTasks() {
        const tasksJson = localStorage.getItem('tasks');
        return tasksJson ? JSON.parse(tasksJson) : [];
    }

    saveTask(task) {
        const tasks = this.getTasks();
        tasks.push(task);
        localStorage.setItem('tasks', JSON.stringify(tasks));
    }

    updateEmptyState() {
        const tasks = this.getTasks();
        if (tasks.length === 0) {
            this.showEmptyState();
        } else {
            this.hideEmptyState();
        }
    }

    showEmptyState() {
        if (document.getElementById('emptyState')) return;

        const emptyDiv = document.createElement('div');
        emptyDiv.id = 'emptyState';
        emptyDiv.textContent = '暂无任务，添加一个开始吧！';
        this.taskList.appendChild(emptyDiv);
    }

    hideEmptyState() {
        const emptyDiv = document.getElementById('emptyState');
        if (emptyDiv) {
            emptyDiv.remove();
        }
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    new TaskManager();
});